package no.ntnu.fp.testing;

import static org.junit.Assert.*;

import java.sql.Connection;
import java.util.ArrayList;

import no.ntnu.fp.gui.FactoryProjectPanel;
import no.ntnu.fp.gui.SoftwarePanel;
import no.ntnu.fp.model.FactoryProject;
import no.ntnu.fp.model.Software;
import no.ntnu.fp.storage.FactoryDbStorage;
import no.ntnu.fp.storage.SoftwareDbStorage;

import org.junit.Before;
import org.junit.Test;

public class SoftwareDbStorageTest {
	SoftwareDbStorage sdb;
	FactoryProject fpb;
	Connection con;
	@Before
	public void setUp() throws Exception {
		sdb = new SoftwareDbStorage();
		con = sdb.connectToFactoryDb();
	}

	@Test
	public void testSoftwareDbStorage() {
		assertNotNull(con.toString());
		assertTrue(sdb instanceof SoftwareDbStorage);
	}


	@Test
	public void testOpenSoftware() {
		ArrayList<Software> a = sdb.openSoftware();
		assertNotNull(a);
	}

	@Test
	public void testAddSoftware() {
		ArrayList<Software> fa = sdb.openSoftware();
		int id=fa.size();
		Software so = new Software(id+1, 0, "");
		System.out.println("Add:"+so.getSwVersion());
		//System.out.println(sdb.addSoftware(so, null));
		int tmp = 0;
		sdb.addSoftware(so, null);
		fa = sdb.openSoftware();
		for(Software s:fa){
			if(s.getSwVersion()==id+1){
				tmp = 1;
				System.out.println("found:"+s.getSwVersion());
				assertTrue(so.getSwVersion() == s.getSwVersion());
				
			}
		}
		if(tmp==0){
			fail();
		}
		
		//System.out.println(asd.getSubVersion());
		//assertTrue(fa.get(id)==so);
		//sdb.addSoftware(new Software(fa.size()+1, 0, ""), null);
	}

	@Test
	public void testSwInSwArchive() {
		ArrayList<Software> fa = sdb.openSoftware();
		int id=fa.size();
		Software so = new Software(id+1, 0, "");
		System.out.println("SwIn:"+so.getSwVersion());
		//System.out.println(sdb.addSoftware(so, null));
		
		System.out.println(sdb.addSoftware(so,null)); 
		
		assertTrue(sdb.swInSwArchive(so.getSwVersion()));	 
		}

	

	@Test
	public void testGetBiggestSubId() {
		ArrayList<Software> fa = sdb.openSoftware();
		int biggest = 0;
		for(Software s:fa){
			int tmp = s.getSubVersion();
			if(tmp>biggest){
				biggest=tmp;
				System.out.println(biggest);
			}
		}
		FactoryProject qwe = sdb.openFactoryProject();
		FactoryDbStorage fdbs = new FactoryDbStorage();
		//fProjectPanel.setModel(fdbs.openFactoryProject());
		
		int id=fa.size();
		Software so = new Software(id+1, biggest+1, "");
		System.out.println("biggest:"+so.getSwVersion()+"::"+so.getSubVersion());
		System.out.println(sdb.getBiggestSubId(so.getSwVersion()));
		
		//FactoryProjectPanel fac = new FactoryProjectPanel();
		//fac.setModel(fdbs.openFactoryProject());
		//SoftwarePanel panel= new SoftwarePanel(fac);
		
		sdb.addSoftware(so, null);
		
		assertEquals(0, sdb.getBiggestSubId(-5));
		assertEquals(so.getSubVersion(), sdb.getBiggestSubId(so.getSwVersion()));



	
	}

}
